package com.auto.api.mapping.filter;

import com.auto.api.core.constants.MockTypeConstants;
import com.auto.api.core.entity.BaseApiInfo;
import com.auto.api.common.utils.JsonMapper;
import com.auto.api.core.service.ApiInfoService;
import com.auto.api.core.util.SpringContextHolder;
import com.fasterxml.jackson.databind.JsonNode;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Description:模拟数据过滤器
 *
 * @author liangshf
 * @date 2021-11-26
 */
public class MockFilter implements Filter{

    public void init(FilterConfig arg0) {
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String uri = request.getRequestURI();
        ApiInfoService mappingService = SpringContextHolder.getBean(ApiInfoService.class);
        BaseApiInfo methodItem = mappingService.getApiByUrl(uri);
        if (methodItem == null || methodItem.getMockType() == MockTypeConstants.MOCK_TYPE_N) {
            filterChain.doFilter(request, response);
            return;
        }
        JsonNode jsonNode = JsonMapper.getObjectMapper().readTree(methodItem.getMockResultJson());
        response.getOutputStream().write(JsonMapper.toJson(jsonNode).getBytes());
    }

    public void destroy() {
    }
}
